package com.qxzn.module.mine.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.page.widget.VerificationCodeView;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VerificationCode extends BaseActivity {
    public static String EXTRA_TITLE = "extra_title";
    public static String EXTRA_TITLE_SUB = "extra_title_sub";
    public static String EXTRA_CODE = "extra_code";
    public static String EXTRA_NAME_PROMPT = "extra_name_prompt";
    public static String EXTRA_ACTIVITY = "extra_activity";
    public static String EXTRA_PHONE = "extra_phone";
    public static String EXTRA_TYPE_int = "extra_type";
    public static String EXTRA_ACTIVITY_PARAMS = "extra_activity_params";

    @BindView(R2.id.vcv_code)
    VerificationCodeView vcvCode;
    @BindView(R2.id.tv_resend)
    TextView tvResend;
    @BindView(R2.id.title_shadow)
    View title_shadow;
    @BindView(R2.id.tv_target_title)
    TextView titleView;
    @BindView(R2.id.tv_target_title_sub)
    TextView titleViewSub;
    @BindView(R2.id.tv_cancel_btn)
    TextView tv_cancel_btn;
    @BindView(R2.id.tv_target_phone)
    TextView phoneView;
    @BindView(R2.id.tv_error_prompt)
    TextView promptView;
    @BindView(R2.id.tv_name_prompt)
    TextView tv_name_prompt;


    private CountDownTimer timer;
    private String phone;
    private int type;

    @Override
    protected int initLayout() {
        return R.layout.activity_verification_code;
    }

    @Override
    protected void initView() {
        String titleSub = getIntent().getStringExtra(EXTRA_TITLE_SUB);
        if (TextUtils.isEmpty(titleSub)) {
            title_bar.setVisibility(View.GONE);
            titleView.setVisibility(View.VISIBLE);
            titleViewSub.setVisibility(View.VISIBLE);
            tv_cancel_btn.setVisibility(View.VISIBLE);
            titleView.setText(getIntent().getStringExtra(EXTRA_TITLE));
        } else {
            title_shadow.setVisibility(View.VISIBLE);
            tv_title.setText(titleSub);
        }
        String name = getIntent().getStringExtra(EXTRA_NAME_PROMPT);
        if (!TextUtils.isEmpty(name)) {
            tv_name_prompt.setText("短信到" + name + "的手机：");
        }
        phone = getIntent().getStringExtra(EXTRA_PHONE);
        type = getIntent().getIntExtra(EXTRA_TYPE_int, 3);
        phoneView.setText("+86 " + CommonUtil.getSecurityPhoneString(phone));
        vcvCode.enableSystemInput(false);
        vcvCode.setCompleteListener(code -> {
//            if ("888888".equals(code))
//                startActivity(new Intent()
//                        .setComponent(new ComponentName(VerificationCode.this, getIntent().getStringExtra(VerificationCode.EXTRA_ACTIVITY)))
//                        .putExtra(EXTRA_TITLE, getIntent().getStringExtra(EXTRA_TITLE))
//                        .putExtra(EXTRA_PHONE, phone)
//                        .putExtra(EXTRA_ACTIVITY_PARAMS, getIntent().getStringExtra(EXTRA_ACTIVITY_PARAMS)));
//            else {
//                error();
//            }
            verifyCode(code);
        });
    }

    private void error() {
        vcvCode.clear();
        promptView.setVisibility(View.VISIBLE);
    }

    private void countDownTimer() {
        if (timer == null) {
            timer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    tvResend.setText("重新发送(" + millisUntilFinished / 1000 + "s)");
                }

                @Override
                public void onFinish() {
                    tvResend.setEnabled(true);
                    tvResend.setText("点击重新发送");
                    tvResend.setTextColor(getResources().getColor(R.color.blue_2A8CFF));
                }
            };
        } else {
            timer.cancel();
        }
        timer.start();
        tvResend.setEnabled(false);
        tvResend.setTextColor(getResources().getColor(R.color.gray_FF999999));
    }

    @OnClick({R2.id.tv_resend, R2.id.tv_cancel_btn})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) return;
        int i = view.getId();
        if (i == R.id.tv_resend) {
            requestCode();
        } else if (i == R.id.tv_cancel_btn) {
            finish();
        }
    }

    private void requestCode() {
        showProgress();
        vcvCode.clear();
        JSONObject params = new JSONObject();
        params.put("phone", phone);
        params.put("type", type);
        HttpRequest.getService().getCode(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                hideProgress();
                BaseBean baseBean = response.body();
                if (baseBean != null) {
                    if (baseBean.getCode() == 200) {
                        ToastUtil.showTextToast(VerificationCode.this, "验证码发送成功");
                        countDownTimer();
                        return;
                    }
                }
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    ToastUtil.showTextToast(VerificationCode.this, baseBean.getMsg());
                } else {
                    ToastUtil.showTextToast(VerificationCode.this, "验证码发送失败，请重试");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                hideProgress();
                ToastUtil.showTextToast(VerificationCode.this, getString(R.string.network_error));
            }
        });
    }


    public void verifyCode(String code) {
        showProgress();
        JSONObject params = new JSONObject();
        params.put("username", phone);
        params.put("code", code);
        params.put("type", type);
        HttpRequest.getService().verifyCode(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                hideProgress();
                BaseBean baseBean = response.body();
                if (baseBean != null) {
                    if (baseBean.getCode() == 200) {
                        startActivity(new Intent()
                                .setComponent(new ComponentName(VerificationCode.this, getIntent().getStringExtra(VerificationCode.EXTRA_ACTIVITY)))
                                .putExtra(EXTRA_TITLE, getIntent().getStringExtra(EXTRA_TITLE))
                                .putExtra(EXTRA_PHONE, phone)
                                .putExtra(EXTRA_ACTIVITY_PARAMS, getIntent().getStringExtra(EXTRA_ACTIVITY_PARAMS)));
                        vcvCode.clear();
                        return;
                    }
                }
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    ToastUtil.showTextToast(VerificationCode.this, baseBean.getMsg());
                } else {
                    ToastUtil.showTextToast(VerificationCode.this, "验证码不正确");
                }
                error();
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                hideProgress();
                ToastUtil.showTextToast(VerificationCode.this, getString(R.string.network_error));
            }
        });
    }

    @Override
    protected void iniTitleBar() {
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        requestCode();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    public void onClickKeyPad(View view) {
        int id = view.getId();
        int length = vcvCode.getLength();
        if (id == com.qxzn.app.page.R.id.number_D) {
            if (length > 0) {
                vcvCode.getEditText().getText().delete(length - 1, length);
            }
        } else if (length < 6) {
            if (view instanceof TextView) {
                vcvCode.getEditText().getText().append(((TextView) view).getText());
            }
        }
    }

}
